<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools title="总记录数: 16 条">
          <el-button type="warning" size="small" @click="$router.push('/import')" v-allow="import_excel">excel导入</el-button>
          <el-button type="danger" size="small" @click="hExportExcel" v-allow="export_excel">excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="employees" :default-sort="{ prop:'workNumber'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template slot-scope="scope">
              <image-holder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber"/>
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template slot-scope="scope">
              {{ format(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName"/>
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <!-- <el-table-column label="账户状态" prop="username"/> -->
          <el-table-column label="操作" width="280">
      <template slot-scope="scope">
        <el-button type="text" size="small" @click="$router.push('/employees/detail?id=' + scope.row.id)">查看</el-button>
        <el-button type="text" size="small" @click="hAssign(scope.row.id)">分配角色</el-button>
        <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="size"
          :page-sizes="[2,5,10]"
          @current-change="hCurrentChange"
          @size-change="hSizeChange"
        />
        </el-row>
      </el-card>
    </div>

    <el-dialog 
    title="新增员工" 
    :visible.sync="showDialog" 
    @close="hClose"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    >
      <EmpDialog @close="showDialog=false" @success="hSuccess" ref="empDialog" />
    </el-dialog>

    <el-dialog :visible.sync="showDialogRole">
      <assign-role :curId="curId" v-if="showDialogRole" @success="hSuccessRole" />
    </el-dialog>
  </div>
</template>
<script>
// 导入前面封装的组件 PageTools
// import PageTools from '@/components/PageTools/index.vue'
import { getEmployee, delEmployee } from '@/api/employees.js' 
import { TYPE_MAP } from '@/constant/index'
import EmpDialog from './empDialog'
// 引入组件
import AssignRole from './assignRole.vue'
export default {
  components: {
    'EmpDialog': EmpDialog,
    AssignRole // 注册组件
  },
  created() {
    // console.log('created', this.num)
    // this.hello()
    this.loadEmployee()
  },
  methods: {
    hSuccessRole() {
      this.showDialogRole = false
      this.$message.success('保存成功')
    },
    hAssign(id) {
      this.showDialogRole = true
      this.curId = id
    },
    formatData(rows) {
      // const header = []
      // const data = []
      // 表头
      // 英文的表头, 要转换为中文
      const enHeader = Object.keys(rows[0])
      const mapObj = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const header = enHeader.map(en => mapObj[en])
      // 内容
      const data = rows.map(obj => {
        // obj.formOfEmployment =====> 1, 2
        obj.formOfEmployment = TYPE_MAP[obj.formOfEmployment]
        return Object.values(obj)
      })
      return { header, data }
    },
     async hExportExcel() {
      // 1. 发请求拿数据
      const res = await getEmployee(this.page, this.size)  
      // 2. 对数据进行格式转换
      const { header, data } = this.formatData(res.data.rows)
      // 3. 导出
      console.log('员工信息', header, data)
      import('@/vendor/Export2Excel').then(excel => {
      // excel表示导入的模块对象
      console.log(excel)
      excel.export_json_to_excel({
        header, // 表头 必填
        data, // 具体数据 必填
        filename: '员工信息', // 文件名称
        autoWidth: true, // 宽度是否自适应
        bookType: 'xlsx' // 生成的文件类型
      })
    })
    },
    hClose() {
      // 清空子组件的表单数据 & 校验结果
      // 思路: 在子组件内部提供一个方法, 在父组件调用
      this.$refs.empDialog.resetForm()
    },
    hSuccess() {
      this.$message.success('子组件添加成功')
      // 关闭弹层, 更新数据
      this.showDialog = false
      this.loadEmployee()
    },
    format(type) {
      return TYPE_MAP[type] || '未知'
    },
    async doDel(id) {
      try {
        // 1. 调用接口做删除
        const res = await delEmployee(id)
        console.log('delEmployee', res)
        // 如果当前删除是表格中最后一条数据,页面会显示不正常
        if (this.employees.length === 1) {
          if (this.page > 1) {
            this.page--
          }
        }
        // 2. 提示用户, 删除成功了
        this.$message.success('删除成功')
        // 重发请求
        this.loadEmployee()
      } catch (err) {
        console.log('delEmployee', err)
      }
    },

    hDel(id) {
      console.log(id)
      this.$confirm('确认删除吗？').then(() => {
        this.doDel(id)
      }).catch(() => {})
    },
    // 会自动接收当前点击的页码
    hCurrentChange(curPage) {
      // alert(curPage)
      // 1. 更新页码
      this.page = curPage
      // 2. 重发请求
      this.loadEmployee()
    },
    // 每页几条
    hSizeChange(curSize) {
      // alert(size)
      // 1. 更新每页的条数
      this.size = curSize
      // 2. 重发请求
      this.loadEmployee()
    },
    async loadEmployee() {
      try {
        const res = await getEmployee(this.page, this.size)
        console.log('loadEmployee', res)
        this.employees = res.data.rows

        this.total = res.data.total
      } catch (err) {
        console.log(err)
      }
    },
  },
  data() {
    return {
      employees : [],
      total: 0, // 总共数据条数
      page: 1,  // 当前页码
      size: 5,  // 每页几条
      showDialog: false,
      showDialogRole: false,
      curId: '' // 当前的员工编号
    }
  }

}
</script>